<?php
/* 
    腾讯云直播回调
 */

namespace app\appapi\controller;

use cmf\controller\HomeBaseController;
use think\facade\Db;


class LivebackController extends HomeBaseController
{
    public function index(){
        $data = $this->request->param();
        $this->callbacklog('data:'.json_encode($data));
        $rs = array( 'code' => 0 );
        
        if(!$data){
			$this->callbacklog("request para json format error");
			$rs['code']=4001;
			echo json_encode($rs);	
			exit;
		}
		
		if(array_key_exists("t",$data)
				&& array_key_exists("sign",$data)
				&& array_key_exists("event_type",$data) 
				&& array_key_exists("stream_id",$data))
		{
			$check_t = $data['t'];
			$check_sign = $data['sign'];
			$event_type = $data['event_type'];
			$stream_id = $data['stream_id'];
		}else {
			$this->callbacklog("request para error");
			$rs['code']=4002;
			echo json_encode($rs);	
			exit;
		}
		$md5_sign = $this-> GetCallBackSign($check_t);
		if( !($check_sign == $md5_sign) ){
			$this->callbacklog("check_sign error:" . $check_sign . ":" . $md5_sign);
			$rs['code']=4003;
			echo json_encode($rs);
			exit;
		}        
		
		if($event_type == 100){
			/* 回放回调 */
			if(array_key_exists("video_id",$data) && 
					array_key_exists("video_url",$data) &&
					array_key_exists("start_time",$data) &&
					array_key_exists("end_time",$data) ){
						
				$video_id = $data['video_id'];
				$video_url = $data['video_url'];
				$start_time = $data['start_time'];
				$end_time = $data['end_time'];
			}else{
				$this->callbacklog("request para error:回放信息参数缺少" );
				$rs['code']=4002;
				echo json_encode($rs);	
				exit;
			}
		}     
		$ret=0;
		if($event_type == 0){        	
			/* 断流 */
			$ret=$this->stopConversa($stream_id);
		}elseif ($event_type == 1){
            /* 推流 */

		}elseif ($event_type == 8){
            /* 混流 */

		}elseif ($event_type == 200){
            /* 直播截图生成 */
			$channel_id=$data['channel_id'];
			$create_time=$data['create_time'];
			$pic_url=$data['pic_url'];
			$sign=$data['sign'];
			$stream_id=$data['stream_id'];
			$img_time=$data['t'];
			$pic_full_url=$data['pic_full_url'];
			$data2=array(
				"stream_id"=>$stream_id,
				"pic_url"=>$pic_url,
				"create_time"=>$create_time,
				"pic_full_url"=>$pic_full_url,
			);										
			Db::name('user_screenshot')->insert($data2);
			$ret=0;

		}elseif ($event_type == 100){
            /* 录制生成 */
			//$duration = $end_time - $start_time;
			//if ( $duration > 60 ){
				$data=array(
					"video_url"=>$video_url,
					//"duration"=>$duration,
					//"file_id"=>$video_id,
				);
		}
        $this->callbacklog($ret );
		$rs['code']=0;
		echo json_encode($rs);
		exit;

    }
    protected function GetCallBackSign($txTime){
		$configpri=getConfigPri();
		$md5_val = md5($configpri['tx_api_key'] . strval($txTime));
		return $md5_val;
	}
	protected function callbacklog($msg){
		file_put_contents(CMF_ROOT .'log/Liveback_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 '.$msg."\r\n",FILE_APPEND);
	}
    protected function stopConversa($stream){
        if($stream==''){
            return 4004;
        }
        $stream_a=explode('_',$stream);
        $uid=$stream_a[0];
        $showid=$stream_a[1];
        
        if(!$uid || !$showid){
            return 4005;
        }
        $this->callbacklog('stream:'.json_encode($stream));
        $this->callbacklog('uid:'.json_encode($uid));
        $this->callbacklog('showid:'.json_encode($showid));
        $info=Db::name('conversa_log')
                ->where(" ( uid={$uid} or liveuid={$uid} ) and showid='{$showid}'")
                ->find();
        $this->callbacklog('info:'.json_encode($info));
		
		 
		
        if(!$info){
            return 4006;
        }
        if($info['status'] ==2){
            return 4007;
        }
        
        $nowtime=time();

        $data=[
            'status'=>2,
            'endtime'=>$nowtime,
        ];
        $length=$nowtime - $info['starttime'];
        $sendtype='0'; //用户给主播发
        if($uid==$info['liveuid']){
            $sendtype='1'; //主播给用户发
            if($length < 10){
                $votes=$info['total'];
                reduceVotes($info['liveuid'],$votes,$votes);
                
                Db::name('user_coinrecord')
                    ->where("action in (2,3) and touid = {$info['liveuid']} and showid={$showid}")
                    ->update(['isdeduct'=>1]);

                $data['total']='0';
            }
        }
        
        Db::name('conversa_log')->where("id={$info['id']}")->update($data);
        
        Db::name('user')->where("id={$info['uid']}")->update( ['online'=>3] );
        Db::name('user')->where("id={$info['liveuid']}")->update( ['online'=>3] );
        
 
        $content=lang('通话时长 ').getLength($length,2);
	
        
 
        /* IM */
        /* 用户给主播发 */
        $ext=[
            'method'=>'call',
            'action'=>'9',
            'type'=>$info['type'],
            'content'=>$content,
        ];
        
        #构造高级接口所需参数
        $msg_content = array();
        //创建array 所需元素
        $msg_content_elem = array(
            'MsgType' => 'TIMCustomElem',       //自定义类型
            'MsgContent' => array(
                'Data' => json_encode($ext),
                'Desc' => '',
            )
        );
        //将创建的元素$msg_content_elem, 加入array $msg_content
        array_push($msg_content, $msg_content_elem);
        
        $account_id=(string)$info['uid'];
        $receiver=(string)$info['liveuid'];
        $api=getTxRestApi();
        $type= $sendtype==0 ? 1 : 2;
        $ret = $api->openim_send_msg_custom($account_id, $receiver, $msg_content,$type);
		
		

        
        /* 主播给用户发 */
        $ext=[
            'method'=>'call',
            'action'=>'8',
            'type'=>$info['type'],
            'content'=>$content,
        ];
        
        #构造高级接口所需参数
        $msg_content = array();
        //创建array 所需元素
        $msg_content_elem = array(
            'MsgType' => 'TIMCustomElem',       //自定义类型
            'MsgContent' => array(
                'Data' => json_encode($ext),
                'Desc' => '',
            )
        );
        //将创建的元素$msg_content_elem, 加入array $msg_content
        array_push($msg_content, $msg_content_elem);
        
        $account_id=(string)$info['liveuid'];
        $receiver=(string)$info['uid'];
        $api=getTxRestApi();
        $type= $sendtype==1 ? 1 : 2;
        $ret = $api->openim_send_msg_custom($account_id, $receiver, $msg_content,$type);
        
        return 0;
    }
	//涉黄关播及拉黑处理
	protected function JianhuangStopConversa($info){
		
        /*if(!$live==''){
            return 4004;
        }
        $stream_a=explode('_',$stream);
        $uid=$stream_a[0];
        $showid=$stream_a[1];
        
        if(!$uid || !$showid){
            return 4005;
        }
   
        $info=Db::name('conversa_log')
                ->where(" ( uid={$uid} or liveuid={$uid} ) and showid='{$showid}'")
                ->find();*/
        $this->jianhuangcallbacklog('info:'.json_encode($info));
		
        if(!$info){
            return 4006;
        }
        if($info['status'] ==2){
            return 4007;
        }
        
        $nowtime=time();

        $data=[
            'status'=>2,
            'endtime'=>$nowtime,
        ];
        $length=$nowtime - $info['starttime'];
        $sendtype='0'; //用户给主播发
        if($uid==$info['liveuid']){
            $sendtype='1'; //主播给用户发
            if($length < 10){
                $votes=$info['total'];
                reduceVotes($info['liveuid'],$votes,$votes);
                
                Db::name('user_coinrecord')
                    ->where("action in (2,3) and touid = {$info['liveuid']} and showid={$showid}")
                    ->update(['isdeduct'=>1]);

                $data['total']='0';
            }
        }
        
        Db::name('conversa_log')->where("id={$info['id']}")->update($data);
        Db::name('user')->where("id={$info['uid']}")->update( ['online'=>0] );
        Db::name('user')->where("id={$info['liveuid']}")->update( ['online'=>0] );
		
		
		//拉黑逻辑处理
		$this->reflect_block($info['uid']);
		$this->reflect_block($info['liveuid']);
		

        $content=lang('内容涉嫌违规,账号已被禁用! ');
        /* IM */
        /* 用户给主播发 */
        $ext=[
            'method'=>'call',
            'action'=>'110',
            'type'=>$info['type'],
            'content'=>$content,
        ];
        
        #构造高级接口所需参数
        $msg_content = array();
        //创建array 所需元素
        $msg_content_elem = array(
            'MsgType' => 'TIMCustomElem',       //自定义类型
            'MsgContent' => array(
                'Data' => json_encode($ext),
                'Desc' => '',
            )
        );
        //将创建的元素$msg_content_elem, 加入array $msg_content
        array_push($msg_content, $msg_content_elem);
        
        $account_id=(string)$info['uid'];
        $receiver=(string)$info['liveuid'];
        $api=getTxRestApi();
        $type= $sendtype==0 ? 1 : 2;
        $ret = $api->openim_send_msg_custom($account_id, $receiver, $msg_content,$type);
		
		

        
        /* 主播给用户发 */
        $ext=[
            'method'=>'call',
            'action'=>'110',
            'type'=>$info['type'],
            'content'=>$content,
        ];
        
        #构造高级接口所需参数
        $msg_content = array();
        //创建array 所需元素
        $msg_content_elem = array(
            'MsgType' => 'TIMCustomElem',       //自定义类型
            'MsgContent' => array(
                'Data' => json_encode($ext),
                'Desc' => '',
            )
        );
        //将创建的元素$msg_content_elem, 加入array $msg_content
        array_push($msg_content, $msg_content_elem);
        
        $account_id=(string)$info['liveuid'];
        $receiver=(string)$info['uid'];
        $api=getTxRestApi();
        $type= $sendtype==1 ? 1 : 2;
        $ret = $api->openim_send_msg_custom($account_id, $receiver, $msg_content,$type);
        
        return 0;
    }
	
	///  鉴黄
	public function jianhuang(){
		$result = array( 'code' => 0 );
		$request = file_get_contents("php://input");
		$data = json_decode($request, true);
		$this->jianhuangcallbacklog('request:'.$request);
		/* file_put_contents('./jianhuangjietu.txt',date('y-m-d H:i:s').' 提交参数信息 jianhuang====:'.$request."\r\n",FILE_APPEND); */
		

		if(!$data){
			$this->jianhuangcallbacklog("request para json format error");
			$result['code']=4001;
			echo json_encode($result);	
			exit;
		}
	
		
		$tid=$data['tid'];
		$streamId=$data['streamId'];
		$channelId=$data['channelId'];
		$img=$data['img'];
		$type=$data['type'][0];
		$confidence=$data['confidence'];
		$normalScore=$data['normalScore'];
		$pornScore=$data['pornScore'];
		$hotScore=$data['hotScore'];
		$level=$data['level'];
		$screenshotTime=$data['screenshotTime'];
		$ocrMsg=$data['ocrMsg'];
		$sendTime=$data['sendTime'];
		
		
		//主播或用户ID
		$liveinfo=explode('_',$streamId);
		$userId=$liveinfo[0];
		$showid=$liveinfo[1];
		
		
		
		$info=array(
			
			"userid"=>$userId,
			"touserid"=>$userId,
			"tid"=>$tid, //预警策略 ID，视频内容预警：20001
			"roomid"=>$streamId,  //流名称
			"img"=>$img, //预警图 片链接
			"type"=>$type, //图片类型，0：正常图片，1 - 5：不合宜图片
			"confidence"=>$confidence, //涉黄置信度，范围 0-100；normalScore， hotScore， pornScore 的综合评分
			"normalscore"=>$normalScore, //图片为正常图片的评分
			"hotscore"=>$hotScore, //图片为性感图片的评分
			"pornscore"=>$pornScore, //图片为色情图片的评分
			"level"=>$level, //图片的级别
			"ocrmsg"=>$ocrMsg, //图片的 OCR 识别信息（如果存在）
			"screenshottime"=>$screenshotTime, //截图时间
			"sendtime"=>$sendTime, //请求发 送时间 ，Unix 时间戳
		);
		
		
		//查询通话信息
		$live=Db::name('conversa_log')
                ->where(" ( uid={$userId} or liveuid={$userId} ) and showid='{$showid}'")
                ->find();
		if(!$live){
			return 0;
		}else if($live['uid']==$userId){
			$info['userid']=$live['uid'];
			$info['touserid']=$live['liveuid'];
		}else{
			$info['userid']=$live['liveuid'];
			$info['touserid']=$live['uid'];
		}

		
		if($type>0){   //当为不合宜图片时请求
			/* 逻辑处理 */
			$ret=$this->JianhuangStopConversa($live);
			
			if($ret==0){
				$info['status']=1;
				$info['uptime']=time();
			}
		}
		$data=Db::name('user_jianhuang')->insert($info);
		
		echo json_encode($result);	
		exit;
		
	}
	
	
	//拉黑逻辑处理
	public function reflect_block($uid){
	/*public function reflect_block(){	
		$data = $this->request->param(); 
		$uid=$data['uid'];*/
		
		
		//获取私密配置
		$config=getConfigPri();
		$block_count=$config['block_count'];   //拉黑次数  当次数为0时默认为永久拉黑
		$block_time=$config['block_time']; //拉黑时间配置
		$arr = explode(',',$block_time);
		
		$time=time();
		$reflect=Db::name('user_reflect_block')
			->where("uid={$uid}")
			->find();
		if($reflect){
			
			//判断是否被永久拉黑或者是拉黑未到时长
			if($reflect['expiretime']==0 || $reflect['expiretime']>$time){
				return 0;
			}
			
			$count=$reflect['count']+1;
			$expiretime=0;
			if($arr[$reflect['count']]>0 && $block_count!=0){
				$expiretime=$time+$arr[$reflect['count']]*60;
			}
			$data=array(
				"uid"=>$uid, 
				"addtime"=>$time, 
				"expiretime"=>$expiretime, 
				"count"=>$count, 
			);

			if($count>$block_count){
				$data['count']=$block_count;
				$data['expiretime']=0;
			}
			Db::name('user_reflect_block')
				->where("uid={$uid}")
				->update($data);
    
		}else{   //没有拉黑数据进行添加
			$expiretime=0;
			$count=0;
			if($arr[0]>0  && $block_count!=0){
				$expiretime=$time+$arr[0]*60;
				$count=1;
			}
			$data=array(
				"uid"=>$uid, 
				"addtime"=>$time, 
				"expiretime"=>$expiretime, 
				"count"=>$count, 
			);
			Db::name('user_reflect_block')->insert($data);
		}
		
		//拉黑用户
		Db::name("user")->where(["id" => $uid, "user_type" => 2])->update(['user_status'=>0]);
		Db::name("user_token")->where(["user_id" => $uid])->delete();
		$key2="token_".$uid;
		delcache($key2);
			
		
	}
	
	//用于鉴黄截图打印日志
	protected function jianhuangcallbacklog($msg){
		file_put_contents(CMF_ROOT .'log/Liveback_jianhuang_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 '.$msg."\r\n",FILE_APPEND);
	}
	
}
